import { app, BrowserWindow, ipcMain } from 'electron';
import path from 'node:path';
import started from 'electron-squirrel-startup';
import { database_init, insert_data, delete_data, update_data, query_data, exec_sql, transaction } from './db/dbmanager.js';

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (started) {
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  // and load the index.html of the app.
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    // mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
    mainWindow.loadFile(path.join(path.resolve(__dirname, '../..'), `../../index.html`));
  }

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // 数据库初始化
  database_test_init();
  // 启动逻辑
  ipcMainHandle();

  // 创建窗口
  createWindow();

  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.

// 交互逻辑
function ipcMainHandle() {
  // 与渲染进程交互, 渲染进程和主进程交互主要是因为渲染进程无法直接访问nodejs等, 主进程无法直接访问HTML DOM
  // 通过交互的方式来进行访问. 这里的helloWorld是主进程与渲染进程交互的标识符, 在渲染进程和主进程中都有相应的定义
  // 在项目代码中使用方式为: 
  // const func = async () => {
  //   const response = await window.electronAPI.helloWorld()
  //   console.log(response) // prints out 'helloWorld'
  // }
  // func()
  ipcMain.handle('helloWorld', (event, message) => {
    console.log(message);
    return message;
  });
}

// 数据库测试初始化
function database_test_init() {
  console.log(`数据库初始化的路径: ${path.resolve(__dirname, '../..')}`)
  database_init(path.join(path.resolve(__dirname, '../..'), 'test.db'));
  try {
    // 创建表
    exec_sql(`CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT,
            email TEXT UNIQUE
    )`);
    insert_data('users', [{ name: '李四', email: 'lisi@example.com' }, { name: '王五', email: 'wangwu@example.com' }]);
    update_data('users', { name: '朱八', email: 'zhuba@example.com' }, 'id = 1');
    delete_data('users');
    transaction(() => {
      insert_data('users', { name: '赵六', email: 'zhaoliu@example.com' });
      insert_data('users', { name: '田七', email: 'tianqi@example.com' });
      throw new Error('手动抛出异常');
    });
    // 查询数据
    console.log(`查询到的数据: ${JSON.stringify(query_data('users'))}`);
  } catch (error) {
    console.log(`异常后查询的数据: ${JSON.stringify(query_data('users'))}`);
  }
}